const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const config = require('./config/env');
const { autoBackup } = require('./controllers/migrationController');
const cron = require('node-cron');

const systemSettingController = require('./controllers/systemSettingController');

// 初始化Express应用
const app = express();

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  
  // 记录请求体
  if (req.body && Object.keys(req.body).length > 0) {
    console.log(`请求体:`, JSON.stringify(req.body));
    
    // 特别记录订单相关请求
    if (req.url.includes('/orders') || req.url.includes('/payment')) {
      const fs = require('fs');
      fs.appendFileSync('./logs/app.log', 
        `\n[${new Date().toISOString()}] ${req.method} ${req.url}\n` +
        `请求体: ${JSON.stringify(req.body, null, 2)}\n`
      );
    }
  }
  
  // 保存原始的res.json方法
  const originalJson = res.json;
  
  // 重写res.json方法以记录响应
  res.json = function(body) {
    console.log(`${new Date().toISOString()} - 响应:`, JSON.stringify(body));
    
    // 特别记录订单相关响应
    if (req.url.includes('/orders') || req.url.includes('/payment')) {
      const fs = require('fs');
      fs.appendFileSync('./logs/app.log', 
        `响应: ${JSON.stringify(body, null, 2)}\n` +
        `--------------------------------------------------\n`
      );
    }
    
    // 如果是错误响应，记录更详细的信息
    if (body && body.status === 'error') {
      const fs = require('fs');
      fs.appendFileSync('./logs/app.log', 
        `\n[${new Date().toISOString()}] 错误: ${req.method} ${req.url}\n` +
        `错误信息: ${body.message}\n` +
        `详细信息: ${body.error || 'N/A'}\n` +
        `堆栈: ${body.stack || 'N/A'}\n` +
        `--------------------------------------------------\n`
      );
    }
    
    return originalJson.call(this, body);
  };
  
  next();
});

// CORS配置
const corsOptions = {
  origin: ['http://localhost:8081', 'http://localhost:8080', 'http://localhost:5173', 'http://127.0.0.1:5173', 'http://localhost'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
};

// 中间件
app.use(cors(corsOptions));
app.use(helmet({
  contentSecurityPolicy: false,
  crossOriginEmbedderPolicy: false
}));
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// ======= 生产环境请务必注释此段，避免全员自动登录 =======
// app.use((req, res, next) => {
//   // 为所有请求添加默认用户
//   req.user = {
//     id: 1,
//     username: 'admin',
//     name: '管理员',
//     role: 'admin',
//     permissions: ['all']
//   };
//   next();
// });
// ======= 生产环境请务必注释此段，避免全员自动登录 =======



// 静态文件
app.use(express.static(path.join(__dirname, 'public')));

// 添加下载安全中间件
app.use((req, res, next) => {
  // 检查是否是下载请求
  const isDownloadRequest = 
    req.path.includes('/export') || 
    req.path.includes('/download') || 
    req.path.endsWith('.xlsx');
  
  if (isDownloadRequest) {
    // 允许跨域请求
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
  }
  
  next();
});

// API路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/users'));
app.use('/api/products', require('./routes/products'));
app.use('/api/categories', require('./routes/categories'));
app.use('/api/orders', require('./routes/orders'));
app.use('/api/payment-methods', require('./routes/paymentMethods'));
app.use('/api/departments', require('./routes/departments'));
app.use('/api/roles', require('./routes/roleRoutes'));
app.use('/api/channels', require('./routes/channels'));
app.use('/api/reports', require('./routes/reports'));
app.use('/api/reports-enhanced', require('./routes/reports-enhanced'));

app.use('/api/inventory/stock-in', require('./routes/stockIn'));
app.use('/api/inventory/stock-out', require('./routes/stockOut'));
app.use('/api/inventory', require('./routes/inventory'));
app.use('/api/system-settings', require('./routes/systemSettings'));
app.use('/api/price-tools', require('./routes/admin/priceTools'));
app.use('/api', require('./routes/index'));
app.use('/api', require('./routes/promotions'));
app.use('/api/migration', require('./routes/migration'));

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', message: 'Server is running' });
});

// 404处理
app.use((req, res, next) => {
  res.status(404).json({
    status: 'error',
    message: '找不到请求的资源'
  });
});

// 添加全局错误处理中间件
app.use((err, req, res, next) => {
  console.error('全局错误:', err);
  res.status(500).json({
    status: 'error',
    message: '服务器内部错误',
    error: err.message
  });
});

// 配置自动备份任务 - 每天凌晨3点执行
cron.schedule('0 3 * * *', async () => {
  console.log('开始执行定时备份任务...');
  try {
    const result = await autoBackup();
    console.log(`定时备份任务完成，结果: ${result ? '成功' : '失败'}`);
  } catch (error) {
    console.error('定时备份任务执行失败:', error);
  }
});

// 可选：启动时执行一次备份
app.once('ready', async () => {
  console.log('服务器启动，执行初始备份...');
  try {
    await autoBackup();
  } catch (error) {
    console.error('初始备份失败:', error);
  }
});

// 在应用启动时初始化默认系统设置
const PORT = config.PORT || 5000;
app.listen(PORT, '0.0.0.0', async () => {
  console.log(`Server is running on port ${PORT}`);
  
  // 初始化默认系统设置
  await systemSettingController.initDefaultSettings();
});

module.exports = app; 